package com.smartResponse;

import android.widget.*;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.app.Activity;
import android.os.Bundle;
import android.content.*;
import android.database.Cursor;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;


//We need to develop a way to make sure that the same name can not be entered twice.



public class AddLocation extends Activity {
    EventDB db = new EventDB(this);
    static double lng;
    static double lat;
    static String address_extra;
    static double myRadius;
    static boolean changed;
    
	public static void setLocationVars(double latitude, double longitude, String address, double radius, boolean change) {
		lng = longitude;
		lat = latitude;
		address_extra = address;
		myRadius = radius;
		changed = change;
	}
	
		@Override
		public void onCreate(Bundle savedInstanceState) {
		    super.onCreate(savedInstanceState);
		    setContentView(R.layout.addlocationlayout);
		    Spinner spinner = (Spinner) findViewById(R.id.spinner_audio_settings);
		    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.audioSettings, android.R.layout.simple_spinner_item);
		    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		    spinner.setAdapter(adapter);
		    final TextView address = (TextView) findViewById(R.id.l_address);
		    final TextView longitude = (TextView) findViewById(R.id.l_longitude);
		    final TextView latitude = (TextView) findViewById(R.id.l_latitude);
		    final EditText radius = (EditText) findViewById(R.id.l_radius);
		    
		    if (lng == -10000){
	        	address.setText("Enter a value by selecting 'Show Map'");
	        	longitude.setText("Enter a value by selecting 'Show Map'");
	        	latitude.setText("Enter a value by selecting 'Show Map'");
		    }
	        //This code changes address after a new one is added
	        if (changed == true){
		        address.setText(address_extra);
	        	longitude.setText(String.valueOf(lng));
	        	latitude.setText(String.valueOf(lat));
	        	radius.setText(String.valueOf(myRadius));
	        }

		    on_showMap_Button_Click();
	        on_OK_Button_Click();
	        on_Cancel_Button_Click();
}
		private void on_showMap_Button_Click() {
			Button Button = (Button) findViewById(R.id.show_map);
			
			Button.setOnClickListener(new OnClickListener(){
				public void onClick(View v){
					
					Intent in = new Intent(AddLocation.this, LocationMap.class);
					in.putExtra("Activity", "AddLocation");
					startActivityForResult(in,1);
	                }	
			});
		}

		public void on_OK_Button_Click() {
			
			Button Button = (Button) findViewById(R.id.l_ok);
			Button.setOnClickListener(new OnClickListener() {
	 
				public void onClick(View v) {

					//The code below stores the text in the box to a string
				    EditText name = (EditText) findViewById(R.id.l_name);
				    EditText radius= (EditText) findViewById(R.id.l_radius);
				    TextView address = (TextView) findViewById(R.id.l_address);
				    TextView longitude = (TextView) findViewById(R.id.l_longitude);
				    TextView latitude = (TextView) findViewById(R.id.l_latitude);
				    
		        	String et_name = name.getText().toString();
					String et_radius = radius.getText().toString();
					String et_address = address.getText().toString();
		        	String et_longitude = longitude.getText().toString();
		        	String et_latitude = latitude.getText().toString();							 	        		
	        		
				    boolean name_is_valid = true;
				    boolean valid_radius = true;
				    boolean valid_location = true;
				    db.open();
			        Cursor c = db.getAllLocations();
			        while (c.moveToNext())
			        {
			            String results = c.getString(1);
			            if (results.equals(et_name))
			            { 	
			            	 name_is_valid=false;
			            	 }
			        }
			        db.close();
			        if  (et_name == null || et_name.isEmpty()){
			        	name_is_valid = false;
			        }
			        if (name_is_valid == true){	
			            Spinner mySpinner = (Spinner)findViewById(R.id.spinner_audio_settings);
			            String audio = mySpinner.getSelectedItem().toString();	
				        //checks if frequency is valid
			        	if (et_radius == null || et_radius.isEmpty()) {
			        		valid_radius = false;
			        		} else {
			        		   try {
			        		     @SuppressWarnings("unused")
								double num = Double.parseDouble(et_radius);
			        		   }
			        		   catch (NumberFormatException e) {
			        			   valid_radius = false;
			        		   }
			        		}
			        	if (valid_radius == true){
			        		//Checks if the location has been changed
				        	if (et_address == "Enter a value by selecting 'Show Map'" || 
				        		et_longitude =="Enter a value by selecting 'Show Map'" ||
				        		et_latitude == "Enter a value by selecting 'Show Map'") {
				        		valid_location = false;
				        	}
				        	if (valid_location == true){
								InsertTitle(et_name,et_address,et_longitude,et_latitude,et_radius,audio,"Disabled");
								SmartResponseActivity.setCurrentTab(0);
								  Intent home_intent_menu = new Intent(AddLocation.this, SmartResponseActivity.class);
								  startActivity(home_intent_menu);
								  finish();
				        	}
				        	if (valid_location == false){
					        	Context context = getApplicationContext();
					        	CharSequence text = "Please select 'Show Map' and enter a location and try again.";
					        	int duration = Toast.LENGTH_LONG;
					        	Toast toast = Toast.makeText(context, text, duration);
					        	toast.show();	
				        	}

			        	}
			        	if (valid_radius == false){
				        	Context context = getApplicationContext();
				        	CharSequence text = "Please enter a radius, in feet, that you would like around your location (numbers only).";
				        	int duration = Toast.LENGTH_LONG;
				        	Toast toast = Toast.makeText(context, text, duration);
				        	toast.show();				        	
				        }
			        }
			        if (name_is_valid == false)
			        {	
			        	Context context = getApplicationContext();
			        	CharSequence text = "That name is already in use or is invalid, please enter a different name";
			        	int duration = Toast.LENGTH_LONG;

			        	Toast toast = Toast.makeText(context, text, duration);
			        	toast.show();
			        }
				}

			} );
	}
		public void on_Cancel_Button_Click() {
			 
			Button Button = (Button) findViewById(R.id.l_cancel);
	 
			Button.setOnClickListener(new OnClickListener() {
	 
				public void onClick(View v) {
					SmartResponseActivity.setCurrentTab(0);
					  Intent home_intent_menu = new Intent(AddLocation.this, SmartResponseActivity.class);
					  startActivity(home_intent_menu);
					  finish();
				}

			} );
	}
		@Override
		public boolean onKeyDown(int keyCode, KeyEvent event)  {
		    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
				SmartResponseActivity.setCurrentTab(0);
				  Intent home_intent_menu = new Intent(AddLocation.this, SmartResponseActivity.class);
				  startActivity(home_intent_menu);
				  finish();
		        return true;
		    }

		    return super.onKeyDown(keyCode, event);
		}
		public void InsertTitle(String name, String address, String longitude, 
				String latitude, String radius, String audio, String status)
	    {
	    	EventDB db = new EventDB(this);
	        db.open();        
	        db.insertLocation(
	        		name,
	        		address,
	        		longitude,
	        		latitude,
	        		radius,
	        		audio,
	        		status);        
	        db.close();
	    	
	    } 
		
		//The code in the function below checks to see if a new location was added and if so it refreshes the page
	    @Override
	    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	        super.onActivityResult(requestCode, resultCode, data);
	        
	        if(resultCode==1){
			    final TextView address = (TextView) findViewById(R.id.l_address);
			    final TextView longitude = (TextView) findViewById(R.id.l_longitude);
			    final TextView latitude = (TextView) findViewById(R.id.l_latitude);
			    final EditText radius = (EditText) findViewById(R.id.l_radius);
	        	address.setText(address_extra);
	        	longitude.setText(String.valueOf(lng));
	        	latitude.setText(String.valueOf(lat));
	        	radius.setText(String.valueOf(myRadius));

			    Intent refresh = new Intent(AddLocation.this, AddLocation.class);
	            this.finish();
	            startActivity(refresh);

	        }
	        if(resultCode==RESULT_CANCELED){
	            Intent refresh = new Intent(AddLocation.this, AddLocation.class);
	            startActivity(refresh);
	            this.finish();
	        }
	        
	    }
//Menu Layout
		@Override
		public boolean onCreateOptionsMenu(Menu menu) {
			super.onCreateOptionsMenu(menu);
			menu.add(0,1,0,"Home").setIcon(R.drawable.home);
	        menu.add(0,2,0,"Save").setIcon(R.drawable.add_icon);
	        menu.add(0,3,0,"Cancel").setIcon(R.drawable.cancel);
		    return true;
		}
	    @Override
	     public boolean onOptionsItemSelected(MenuItem item) {
	        switch (item.getItemId()) {
	        case 1:
			  Intent home_intent_menu = new Intent(AddLocation.this, MainActivity.class);
			  startActivity(home_intent_menu);
			  return true;
	        case 2:
	        	on_OK_Button_Click();
	        	return true;
	     case 3:
	    	 	on_Cancel_Button_Click();
	            return true;
	          }
			return false;
	    }
}